"""
images.py

this command implements a serie of tools to manage 
cached images on the ftbexplorer server.
"""


import os, sys, logging
import xml.dom.minidom
from optparse import make_option
from sys import stderr
from copy import copy
from django.core.management.base import BaseCommand
from django.utils.encoding import DjangoUnicodeDecodeError
#import ftbexplorer
from ftbexplorer.core.models import Sentence
from django.db.models import *


class Command(BaseCommand):
    help = "Manage cached images"
    
    option_list = BaseCommand.option_list + (
        make_option('--debug', action='store_true', dest='debug', default=False,
            help='Display debug informations'),
    )
    args = '[reset|generate|regenerate]'
    
    def handle(self, *args, **options):
        if len(args) <> 1:
            print self.usage("images")
            exit(1)

        LOGGING_FORMAT="%(asctime)s - %(levelname)s - %(message)s"
        if options.get("debug", False):
            logging.basicConfig(format=LOGGING_FORMAT, level=logging.DEBUG)
        else:
            logging.basicConfig(format=LOGGING_FORMAT, level=logging.INFO)

        sub = args[0]
        if sub == "reset":
            self.remove_all_images()
        elif sub == "generate":
            self.generate_all_images()
        elif sub == "regenerate":
            self.remove_all_images()
            self.generate_all_images()
        else:
            self.usage()
            exit(1)
            
    def remove_all_images(self):
        logging.info("Removing references in database")
        stces = Sentence.objects.all()
        logging.info("(%d row to check)" % len(stces))
        for a_sen in stces:
            if a_sen.tree_image:
                a_sen.tree_image = None
                a_sen.save()
            
        logging.info("removing files")
        path = os.path.join(settings.MEDIA_ROOT, "trees")
        for root, dirs, files in os.walk(path):
            for f in files:
                if f.endswith(".png"):
                    os.remove(os.path.join(root, f))
                    logging.debug("File %s removed" % os.path.join(root, f))
    
    def generate_all_images(self):
        logging.info("Generating images")
        stces = Sentence.objects.filter()
        logging.info("(%d image to generate)" % len(stces))
        for a_sen in stces:
            a_sen.image()
            logging.debug("Image for %s generated." % a_sen)

        
